package com.flex.mobile.timer;

import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.flex.mobile.dao.impl.TimerDao;
import com.flex.mobile.dao.model.TaxiTimer;
import com.flex.mobile.util.SpringContextUtil;

public class TimerLoader {
   OnceTimer onceTimer;
   Timer loadTimer;
   boolean first = true;
   long nextLoadTime = Integer.MAX_VALUE;

   public TimerLoader(OnceTimer oncetimer) {
      this.onceTimer = oncetimer;
   }

   public long getNextLoadTime() {
      return nextLoadTime;
   }

   public void start() {
      loadTimer = new Timer();
      loadTimer.schedule(new TimerTask() {
         public void run() {
            try {
               load();
            } catch (Exception e) {
               e.printStackTrace();
            }
         }
      }, TimerConfig.getFirstLoadDelay(), TimerConfig.getLoadPeriod());
   }

   void load() throws Exception {
      if (first) {
         first = false;
      }
      onceTimer.clear();

      long now = System.currentTimeMillis();
      nextLoadTime = now + TimerConfig.getLoadPeriod() + 5000;
      try {
         load(nextLoadTime);
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

   void load(long beforetime) throws SQLException {
      List<TaxiTimer> list = executeSql(beforetime);
      for (Iterator<TaxiTimer> it = list.iterator(); it.hasNext();) {
         TaxiTimer tr = (TaxiTimer) it.next();
         onceTimer.registeTimer(tr.getTimerID(), tr.getFirstTriggeTime());
      }
   }

   List<TaxiTimer> executeSql(long firstTrigTime) throws SQLException {
      TimerDao timerDao = (TimerDao) SpringContextUtil.getBean("timerDao");
      return timerDao.loadOnceTimer(firstTrigTime);
   }

   public void stop() {
      onceTimer.stop();
      loadTimer.cancel();
   }
}